/*
 * @Author: Ethan
 * @Github: https://github.com/ethanpub
 * @Date: 2019-05-22 17:29:06
 * @LastEditors: Ethan
 * @Blog: https://ethan.pub
 * @LastEditTime: 2019-12-04 10:48:08
 * @Description: 🙏BUG退散🙏
 */
import {
    Module,
    VuexModule,
    Mutation,
    Action,
    getModule
} from 'vuex-module-decorators'
import { setStorage, removeStorage, getToken } from '../utils/storage';
import { getAsyncRoute } from '@/router/permission'
import { message } from 'ant-design-vue'
import { login, getInfo } from '@/services/user'
import store from './index'
import router from '@/router'

@Module({ dynamic: true, store, name: 'GlobalStore' })
class Global extends VuexModule {
    /** 路由表 */
    asyncRoutes: any[] = []
    userInfo: any = { name: 'admin' }
    noticeInfo: any = {
        noticeNum: 0,
        employStatus: ''
    }
    device: string = "Desktop"


    @Mutation
    saveAsyncRoutes(roleRoutes: any) {
        const routes = getAsyncRoute({ roleRoutes })
        router.addRoutes(routes)
        setStorage('asyncRoutes', roleRoutes)
        this.asyncRoutes = routes
    }

    @Mutation
    saveUserInfo(userInfo: {}) {
        this.userInfo = userInfo
    }

    @Mutation
    logout() {
        removeStorage()
        window.location.href = '/'
    }

    @Mutation
    saveNoticeInfo(noticeInfo: {}) {
        this.noticeInfo = noticeInfo
    }

    @Mutation
    saveDeviceType(device: string) {
        this.device = device
    }

    @Action
    async getDeviceType(payload: string) {
        this.saveDeviceType(payload)
    }


    @Action
    async getNoticeInfo() {
        const data = {
            noticeNum: 3,
            employStatus: 'P'
        }
        this.saveNoticeInfo(data)
    }


    @Action
    async login(payload = {}) {
        const res = await login(payload)
        Number(res.code) == 0
            ? (setStorage('Token', res.token), router.push('/form/baseForm'))
            : message.error(res.message)
    }

    @Action
    async getUserInfo(payload = {}) {
        const res = await getInfo(payload)
        res.code == 0
            ? this.saveAsyncRoutes(res.result)
            : message.error(res.message)
    }
}
/**  Global state */

export const GlobalStore = getModule(Global)
